package com.example.sunmiv1.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.RemoteException;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.example.sunmiv1.R;
import com.example.sunmiv1.utils.QR_code;
import com.example.sunmiv1.utils.ThreadPoolManager;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.printUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CollectActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.collect_money)
    TextView collectMoney;
    @BindView(R.id.collect_one)
    TextView collectOne;
    @BindView(R.id.collect_four)
    TextView collectFour;
    @BindView(R.id.collect_seven)
    TextView collectSeven;
    @BindView(R.id.collect_doubleZero)
    TextView collectDoubleZero;
    @BindView(R.id.collect_two)
    TextView collectTwo;
    @BindView(R.id.collect_five)
    TextView collectFive;
    @BindView(R.id.collect_eight)
    TextView collectEight;
    @BindView(R.id.collect_zero)
    TextView collectZero;
    @BindView(R.id.collect_three)
    TextView collectThree;
    @BindView(R.id.collect_six)
    TextView collectSix;
    @BindView(R.id.collect_nine)
    TextView collectNine;
    @BindView(R.id.collect_spot)
    TextView collectSpot;
    @BindView(R.id.collect_fork)
    TextView collectFork;
    @BindView(R.id.collect_clear)
    TextView collectClear;
    @BindView(R.id.collect_confirm)
    TextView collectConfirm;
    @BindView(R.id.linear_moneyPay)
    LinearLayout linearMoneyPay;
    @BindView(R.id.linear_wxPay)
    LinearLayout linearWxPay;
    @BindView(R.id.linear_aliPay)
    LinearLayout linearAliPay;
    @BindView(R.id.linear_vipPay)
    LinearLayout linearVipPay;
    @BindView(R.id.tv_collect_cancel)
    TextView tvCollectCancel;
    @BindView(R.id.linear_collect)
    LinearLayout linearCollect;

    private ACache aCache;
    private Intent intent;
    private Context context;
    private LoadingDialog loadingDialog;
    public static CollectActivity collectActivity;
    private String receive_money = "";
    private String out_trade_no = "";
    private static final String TAG = "CollectActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_collect);
        collectActivity = this;
        context = this;
        aCache = ACache.get(context);
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(context);
        titleBack.setVisibility(View.VISIBLE);
        titleTitle.setText(R.string.collectTitle);
        startQrCode();
    }

    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 11003);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 11003:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    startQrCode();
                    Toast.makeText(this, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @OnClick({R.id.title_back, R.id.collect_one, R.id.collect_four, R.id.collect_seven, R.id.collect_doubleZero, R.id.collect_two,
            R.id.collect_five, R.id.collect_eight, R.id.collect_zero, R.id.collect_three, R.id.collect_six, R.id.collect_nine,
            R.id.collect_spot, R.id.collect_fork, R.id.collect_clear, R.id.collect_confirm,
            R.id.linear_moneyPay, R.id.linear_wxPay, R.id.linear_aliPay, R.id.linear_vipPay, R.id.tv_collect_cancel, R.id.linear_collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.collect_one:
                text("1");
                break;
            case R.id.collect_four:
                text("4");
                break;
            case R.id.collect_seven:
                text("7");
                break;
            case R.id.collect_doubleZero:
                text("00");
                break;
            case R.id.collect_two:
                text("2");
                break;
            case R.id.collect_five:
                text("5");
                break;
            case R.id.collect_eight:
                text("8");
                break;
            case R.id.collect_zero:
                text("0");
                break;
            case R.id.collect_three:
                text("3");
                break;
            case R.id.collect_six:
                text("6");
                break;
            case R.id.collect_nine:
                text("9");
                break;
            case R.id.collect_spot:
                text(".");
                break;
            case R.id.collect_fork:
                if (receive_money.equals("0.")) {
                    receive_money = "";
                    collectMoney.setText("$" + receive_money);
                }
                if (receive_money.length() > 0) {
                    receive_money = receive_money.substring(0, receive_money.length() - 1);
                    collectMoney.setText("$" + receive_money);
                }
                break;
            case R.id.collect_clear:
                receive_money = "";
                collectMoney.setText("$" + receive_money);
                break;
            case R.id.collect_confirm:
                if (TextUtils.isEmpty(receive_money)) {
                    Toast.makeText(context, "請輸入收款金額", Toast.LENGTH_SHORT).show();
                } else if (Double.parseDouble(receive_money) <= 0) {
                    Toast.makeText(context, "請輸入正確的收款金額", Toast.LENGTH_SHORT).show();
                } else {
                    //設置動畫，從自身位置的最下端向上滑動了自身的高度，持續時間爲500ms
                    final TranslateAnimation ctrlAnimation = new TranslateAnimation(
                            TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0,
                            TranslateAnimation.RELATIVE_TO_SELF, 1, TranslateAnimation.RELATIVE_TO_SELF, 0);
                    ctrlAnimation.setDuration(400l);     //設置動畫的過渡時間
                    linearCollect.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            linearCollect.setVisibility(View.VISIBLE);
                            linearCollect.startAnimation(ctrlAnimation);
                        }
                    }, 100);
                }
                break;
            case R.id.linear_moneyPay:
                linearCollect.setVisibility(View.GONE);
                MoneyPay();
                break;
            case R.id.linear_wxPay:
                intent = new Intent(context, PayActivity.class);
                intent.putExtra("money", receive_money);
                intent.putExtra("payType", "1");
                startActivity(intent);
                break;
            case R.id.linear_aliPay:
                intent = new Intent(context, PayActivity.class);
                intent.putExtra("money", receive_money);
                intent.putExtra("payType", "2");
                startActivity(intent);
                linearCollect.setVisibility(View.GONE);
                break;
            case R.id.linear_vipPay:
                intent = new Intent(context, PayActivity.class);
                intent.putExtra("money", receive_money);
                intent.putExtra("payType", "3");
                startActivity(intent);
                break;
            case R.id.tv_collect_cancel:
                linearCollect.setVisibility(View.GONE);
                break;
            case R.id.linear_collect:
                break;
        }
    }

    /*現金支付*/
    private void MoneyPay() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_identity_id",aCache.getAsString("uid"));
            jsonObject.put("pay_type",3);
            jsonObject.put("pay_money", receive_money);
            jsonObject.put("code","");
            jsonObject.put("vip_login_type",1);
            jsonObject.put("vid","");
            jsonObject.put("password","");
            jsonObject.put("card_code","");
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
            }
            HttpUtils.post(context, Common.QUICK_CASHIER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            out_trade_no = json.getString("out_trade_no");
                            if (printUtil.getInstance().woyouService != null) {
                                printInfo();
                            } else {
                                Toast.makeText(context, "機器暫不支持打印", Toast.LENGTH_SHORT).show();
                            }
                            intent = new Intent(context, CompleteActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        linearCollect.setVisibility(View.GONE);
        receive_money = "";
        collectMoney.setText("$" + receive_money);
    }

    private void text(String number) {
        if (receive_money.contains(".")) {
            Log.e(TAG, "text: 3");
            if (!number.equals(".")) {
                Log.e(TAG, "text: 4");
                if (Double.parseDouble(receive_money) >= 0) {
                    Log.e(TAG, "text: 5");
                    receive_money = receive_money + number;
                    Log.e(TAG, "text: receive_money2=" + receive_money);
                }
                int pointIndex = receive_money.indexOf(".");
                if (receive_money.length() - pointIndex > 3) {
                    receive_money = receive_money.substring(0, pointIndex + 3);
                }
            }
            Log.e(TAG, "text: receive_money3=" + receive_money);
        }


        if (receive_money.length() == 0) {
            Log.e(TAG, "text: 1");
            if (number.equals(".")) {
                receive_money = "0.";
            } else if (number.equals("00")) {
                receive_money = "0.";
            } else if (number.equals("0")) {
                receive_money = "0.";
            } else {
                receive_money = receive_money + number;
            }
        } else {
            Log.e(TAG, "text: 2");
            if (!receive_money.contains(".")) {
                receive_money = receive_money + number;
            }
            Log.e(TAG, "text: receive_money1=" + receive_money);
        }

        if (Double.parseDouble(receive_money) > 100000) {
            Log.e(TAG, "text: 5");
            receive_money = "100000.00";
            Toast.makeText(context, "最大付款金額十萬", Toast.LENGTH_SHORT).show();
        }
        collectMoney.setText("$" + receive_money);
    }

    private void printInfo() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        ThreadPoolManager.getInstance().executeTask(() -> {
            try {
                printUtil.getInstance().woyouService.setAlignment(1, null);
                printUtil.getInstance().woyouService.printText("快速收單\n", null);
                printUtil.getInstance().woyouService.setAlignment(0, null);
                printUtil.getInstance().woyouService.printText("支付方式:", null);
                printUtil.getInstance().woyouService.printText("現金支付\n", null);
                printUtil.getInstance().woyouService.printText("支付金額:$" + receive_money + "\n", null);
                printUtil.getInstance().woyouService.printText("支付時間:\n" + formatter.format(curDate) + "\n", null);
                printUtil.getInstance().woyouService.setAlignment(1, null);
                printUtil.getInstance().woyouService.printBitmap(QR_code.createBarcode(out_trade_no, 400, 60), null);
                printUtil.getInstance().woyouService.printBitmap(QR_code.createQRCode(out_trade_no, 300, 300), null);
                printUtil.getInstance().woyouService.printText("\n請謹慎保管此小票，", null);
                printUtil.getInstance().woyouService.lineWrap(5, null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });
    }

}
